package com.ddstation.common.security.interceptor;

import java.io.PrintWriter;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.ddstation.common.access_token.service.AccessTokenService;
import net.sf.json.JSONObject;

/**
 * 卫监系统 app
 * @author ZhengXiaoBin
 * @date 2019年8月2日
 */
public class InvsAppValidateRequestInterceptor implements HandlerInterceptor {
	
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response,
			Object obj,
			Exception ex)
			throws Exception {
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response,
			Object obj, ModelAndView mv) throws Exception {
	}

	public boolean preHandle(
			HttpServletRequest request,
			HttpServletResponse response,
			Object obj) throws Exception {
		
		String sToken = request.getHeader(SHORT_ACCESS_TOKEN);
		
		String errcode = null, errmsg = null;
		
		if (StringUtils.isBlank(sToken)) {
			errcode = "40001";
			errmsg = "token不合法：http header 中没有token数据";
		} else if ("open".equals(sToken)) {
			return true;
		} else if (!accessTokenService.validateShortToken(sToken)) {
			errcode = "40001";
			errmsg = "token不合法：token无效，请重新获取";
		} else {
//			JSONObject param = GetRequestJsonUtils.getRequestJsonObject(request);
//			if (param != null) {
//				String institutionId = param.containsKey("institutionId") ? param.getString("institutionId") : null;
//				String doctorId = param.containsKey("doctorId") ? param.getString("doctorId") : null;
//				if (StringUtils.isNotBlank(institutionId) || StringUtils.isNotBlank(doctorId)) {
//					String[] t = sToken.split("-");
//					if (t == null || t.length < 3) {
//						errcode = "40001";
//						errmsg = "token不合法：token格式不正常";
//					} else {
//						if (StringUtils.isNotBlank(institutionId) && !institutionId.equals(t[0])) {
//							errcode = "40001";
//							errmsg = "token不合法：institutionId和token中的值不一致";
//						}
//						if (StringUtils.isNotBlank(doctorId) && !doctorId.equals(t[1])) {
//							errcode = "40001";
//							errmsg = "token不合法：doctorId和token中的值不一致";
//						}
//					}
//				}
//			}
		}
		
		if (errcode != null) {
			logger.warn("invsapp token无效！ sToken = " + sToken);
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/json; charset=utf-8");
			PrintWriter writer = response.getWriter();
			JSONObject ret = new JSONObject();
			ret.put("errcode", errcode);
			ret.put("errmsg", errmsg);
			
			writer.write(ret.toString());
			writer.flush();
			writer.close();
			return false;
		}
    	return true;
	}
	
	
	private final String SHORT_ACCESS_TOKEN = "short-access-token";
	private final Logger logger = LoggerFactory.getLogger(InvsAppValidateRequestInterceptor.class);
	
	private @Inject AccessTokenService accessTokenService = null;
}
